package com.ruoyi.snmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.snmanagement.mapper.PrinterSnMapper;
import com.ruoyi.snmanagement.domain.PrinterSn;
import com.ruoyi.snmanagement.service.IPrinterSnService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 打印机序列号管理表 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2025-09-24
 */
@Service
public class PrinterSnServiceImpl extends ServiceImpl<PrinterSnMapper, PrinterSn> implements IPrinterSnService {
    @Override
    public List<PrinterSn> getPrinterSnList(PrinterSn printerSn) {

        return baseMapper.selectPrinterList(printerSn);
    }

    @Override
    public int updatePrinterSn(PrinterSn printerSn) {
        try {
            // 设置更新者为当前用户名
            printerSn.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            // 当无法获取当前用户时，使用默认值
            printerSn.setUpdateBy("System");
        }
        // 设置更新时间
        printerSn.setUpdateTime(LocalDateTime.now());
        // 使用 MyBatis-Plus 内置的 updateById 方法
        return this.baseMapper.updateById(printerSn);
    }



    @Override
    public int insertPrinterSn(PrinterSn printerSn) {
        // 设置创建时间
        if (printerSn.getCreateTime() == null) {
            printerSn.setCreateTime(LocalDateTime.now());
        }
        // 设置更新时间
        printerSn.setUpdateTime(LocalDateTime.now());
        // 设置默认状态
        if (printerSn.getDelFlag() == null) {
            printerSn.setDelFlag(0);
        }
        return this.baseMapper.insert(printerSn);
    }

    @Override
    public int deletePrinterSn(Long id) {
        PrinterSn printerSn = new PrinterSn();
        printerSn.setId(id);
        printerSn.setDelFlag(1);
        // 逻辑删除，设置删除标志为1
        printerSn.setUpdateTime(LocalDateTime.now());
        try {
            printerSn.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            printerSn.setUpdateBy("System");
        }
        return this.baseMapper.updateById(printerSn);
    }



    @Override
    public boolean checkSnUnique(PrinterSn printerSn) {
        Long printerSnId = printerSn.getId() == null ? -1L : printerSn.getId();
        LambdaQueryWrapper<PrinterSn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PrinterSn::getSn, printerSn.getSn())
                .ne(PrinterSn::getId, printerSnId)
                .eq(PrinterSn::getDelFlag, 0);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public List<PrinterSn> getPrinterSnListByIds(List<Long> ids) {
        // 实现根据ID列表查询的逻辑
        // 这需要在对应的 Mapper 中添加相应的方法
        return baseMapper.selectPrinterSnListByIds(ids);
    }


//    导入
@Override
@Transactional
public String importPrinterSn(List<PrinterSn> printerSnList, boolean updateSupport) {
    if (printerSnList == null || printerSnList.isEmpty()) {
        throw new RuntimeException("导入数据为空");
    }

    int successNum = 0;
    int failureNum = 0;
    StringBuilder successMsg = new StringBuilder();
    StringBuilder failureMsg = new StringBuilder();

    for (PrinterSn printerSn : printerSnList) {
        try {
            // 检查序列号是否已存在
            PrinterSn existingSn = baseMapper.selectPrinterSnBySn(printerSn.getSn());

            if (existingSn == null) {
                // 新增数据
                printerSn.setRegisterTime(new Date());
                this.save(printerSn);
                // 使用 MyBatis-Plus 提供的 save 方法
                successNum++;
                successMsg.append("\n").append(successNum).append("、序列号 ").append(printerSn.getSn()).append(" 导入成功");
            } else if (updateSupport) {
                // 更新已存在的数据
                printerSn.setId(existingSn.getId());
                baseMapper.updatePrinterSn(printerSn);
                successNum++;
                successMsg.append("\n").append(successNum).append("、序列号 ").append(printerSn.getSn()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("\n").append(failureNum).append("、序列号 ").append(printerSn.getSn()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            failureMsg.append("\n").append(failureNum).append("、序列号 ").append(printerSn.getSn()).append(" 导入失败：").append(e.getMessage());
        }
    }

    if (failureNum > 0) {
        failureMsg.insert(0, "很抱歉！共 " + failureNum + " 条数据格式不正确，错误如下：");
        throw new RuntimeException(failureMsg.toString());
    } else {
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
    }

    return successMsg.toString();
}


}
